//
//  BIDDownloadFile.m
//  shangwuting
//
//  Created by mal on 13-12-25.
//  Copyright (c) 2013年 mal. All rights reserved.
//

#import "BIDDownloadFile.h"
#import "BIDCustomSpinnerView.h"
#import "BIDGlobalMethods.h"

@implementation BIDDownloadFile

@synthesize label;
@synthesize progressView;
@synthesize cancelBtn;
@synthesize downloadView;
@synthesize bgView;
@synthesize spinnerView;
@synthesize urlConnection;
@synthesize fileData;
@synthesize fileName;
@synthesize fileLength;
@synthesize delegate;
@synthesize saveDirectory;

- (void)initData
{
    fileData = [NSMutableData data];
    [self initDownloadView];
}

- (void)initDownloadView
{
    CGSize uploadViewSize = CGSizeMake(300, 0);
    downloadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, uploadViewSize.width, uploadViewSize.height)];
    downloadView.layer.borderWidth = 5;
    downloadView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    downloadView.layer.cornerRadius = 8;
    [downloadView setBackgroundColor:[UIColor colorWithWhite:0.2f alpha:0.8f]];
    
    CGRect ownFrame = downloadView.frame;
    CGSize labelSize = CGSizeMake(ownFrame.size.width, 30);
    CGRect labelFrame = CGRectMake(0, 5, labelSize.width, labelSize.height);
    label = [[UILabel alloc] initWithFrame:labelFrame];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:18.0f];
    label.textColor = [UIColor blackColor];
    label.text = @"正在下载...";
    [label setBackgroundColor:[UIColor clearColor]];
    [downloadView addSubview:label];
    
    CGSize progressViewSize = CGSizeMake(ownFrame.size.width-10, 5);
    CGRect progressViewFrame = CGRectMake(5, label.frame.origin.y+label.frame.size.height+10, progressViewSize.width, progressViewSize.height);
    progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    progressView.frame = progressViewFrame;
    [downloadView addSubview:progressView];
    
    CGSize btnSize = CGSizeMake(150, 20);
    CGRect btnFrame = CGRectMake((ownFrame.size.width-btnSize.width)/2, progressView.frame.origin.y+progressView.frame.size.height+20, btnSize.width, btnSize.height);
    cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //[btn setBackgroundColor:[UIColor clearColor]];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [cancelBtn setTitle:@"取消下载" forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnHandler) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.frame = btnFrame;
    cancelBtn.layer.borderWidth = 1;
    cancelBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    [downloadView addSubview:cancelBtn];
    
    ownFrame.size.height = label.frame.size.height + progressView.frame.size.height + cancelBtn.frame.size.height + 50;
    downloadView.frame = ownFrame;
    
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGRect frame = downloadView.frame;
    frame.origin.x = (screenSize.width-frame.size.width)/2;
    frame.origin.y = (screenSize.height-frame.size.height)/2;
    downloadView.frame = frame;
    
    CGSize spinnerViewSize = CGSizeMake(60, 60);
    CGRect spinnerViewFrame = CGRectMake(0, 0, spinnerViewSize.width, spinnerViewSize.height);
    spinnerView = [[BIDCustomSpinnerView alloc] initWithFrame:spinnerViewFrame];
    spinnerView.content = @"正在保存..";
    [spinnerView initView];
}

//下载文件
- (void)downloadFile:(NSString *)strDownloadURL
{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:bgView];
    [keyWindow addSubview:downloadView];
    [fileData setLength:0];
    [progressView setProgress:0];
    NSURL *url = [NSURL URLWithString:[strDownloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
}

//取消下载
- (void)cancelBtnHandler
{
    [urlConnection cancel];
    [bgView removeFromSuperview];
    [downloadView removeFromSuperview];
}

#pragma mark NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
    if(httpResponse)
    {
        NSDictionary *dictionary = [httpResponse allHeaderFields];
        NSNumber *value = [dictionary objectForKey:@"Content-Length"];
        self.fileLength = [value integerValue];
//        NSString *str = [dictionary objectForKey:@"Content-Disposition"];
//        NSArray *arr = [str componentsSeparatedByString:@"="];
//        self.fileName = [arr objectAtIndex:1];
//        const char* byte = nil;
//        byte = [self.fileName cStringUsingEncoding:NSISOLatin1StringEncoding];
//        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//        self.fileName = [[NSString alloc] initWithCString:byte encoding:enc];
        label.text = [[NSString alloc] initWithFormat:@"正在下载：%@", fileName];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [fileData appendData:data];
    CGFloat rate = [fileData length]*1.0f / fileLength;
    [progressView setProgress:rate animated:YES];
}

//下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [NSThread sleepForTimeInterval:0.5f];
    [bgView removeFromSuperview];
    [downloadView removeFromSuperview];
    
    [spinnerView showTheView];
    //保存文件
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *document = [paths objectAtIndex:0];
        NSString *videoPath = [document stringByAppendingPathComponent:saveDirectory];
        NSFileManager *fileManager = [[NSFileManager alloc] init];
        BOOL flag = [fileManager createDirectoryAtPath:videoPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(flag)
        {
            NSString *filePath = [videoPath stringByAppendingPathComponent:fileName];
            flag = [fileData writeToFile:filePath atomically:YES];
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [spinnerView dismissTheView];
            __block NSString *msg = @"";
            if(flag)
            {
                //msg = @"下载成功";
                [delegate toOpenDoc];
            }
            else
            {
                msg = @"下载失败";
                [BIDGlobalMethods showAlertView:msg buttonTitle:@"关闭" delegate:nil tag:0];
            }
        });
    });
}

//下载出错
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [progressView setProgress:0];
    [fileData resetBytesInRange:NSMakeRange(0, fileData.length)];
    [urlConnection cancel];
    [bgView removeFromSuperview];
    [downloadView removeFromSuperview];
    [BIDGlobalMethods showAlertView:@"下载失败" buttonTitle:@"关闭" delegate:nil tag:0];
}

@end
